package atom;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * Atmoic对象是线程安全的
 * 测试concurrent包下的AtomicInteger
 */
public class AtomicIntegerTest {

  
  public static AtomicInteger atomicInteger = new AtomicInteger(0);// 所有的线程操作同一个对象
  public static int A = 0;

  public static void main(String[] args) throws InterruptedException {
    System.out.println("i累计前" + AtomicIntegerTest.atomicInteger + ",A累计前：" + AtomicIntegerTest.A);
    Thread t0 = new Thread(
            new Runnable() {

              @Override
              public void run() {
                for (int j = 0; j < 100000; j++) {

                  AtomicIntegerTest.A++;
                  AtomicIntegerTest.atomicInteger.getAndIncrement();
                }
              }
            });
    Thread t1 = new Thread(
            new Runnable() {

              @Override
              public void run() {
                for (int j = 0; j < 100000; j++) {

                  AtomicIntegerTest.A--;
                  AtomicIntegerTest.atomicInteger.decrementAndGet();
                }
              }
            });
    t0.start();
    t1.start();
    t0.join();
    t1.join();

    System.out.print("i累计后" + AtomicIntegerTest.atomicInteger + ",A累计后：" + AtomicIntegerTest.A);

  }
}

